import { DataSet } from 'choerodon-ui/pro';

const mapping: any = {
  cdAuditUserIds: {
    name: 'cdAuditUserIds',
    type: 'object',
    label: '审核人员',
    textField: 'realName',
    multiple: true,
    valueField: 'id',
  },
  countersigned: {
    name: 'countersigned',
    type: 'number',
    label: '审核模式',
    defaultValue: 0,
    dynamicProps: {
      required: ({ record }: any) => record?.get('type') === 'cdAudit'
      && record?.get('cdAuditUserIds')?.length > 1,
    },
  },
};

const transformLoadData = (data: any) => {
  const { ciAuditConfig, auditConfig } = data || {};
  const newCdAuditUserIds = ciAuditConfig?.cdAuditUserIds || auditConfig?.cdAuditUserIds;
  return {
    ...data,
    cdAuditUserIds: newCdAuditUserIds && [...newCdAuditUserIds],
    countersigned: ciAuditConfig?.countersigned || 0,
  };
};

const getRequired = (level: any) => (level === 'project' && !window.location.href.includes('project-pipeline-template'));

const getDisabled = (level: any, type: any) => (level !== 'project' || window.location.href.includes('project-pipeline-template')) && !type.includes('cd_');

const Index = (projectId: any, appServiceId: any, originData: any, level: any): any => ({
  autoCreate: true,
  fields: Object.keys(mapping).map((key: any) => {
    const item = mapping[key];
    switch (key) {
      case 'cdAuditUserIds': {
        item.required = (originData.type === 'audit' && getRequired(level)) || originData?.type.includes('cd_');
        item.disabled = getDisabled(level, originData?.type);
        item.options = new DataSet({
          autoQuery: true,
          paging: true,
          pageSize: 1000,
          strictPageSize: false,
          transport: {
            read: ({ dataSet, data, params }: any): any => {
              const realName = data?.realName;
              if (originData?.type.includes('cd_')) {
                return {
                  method: 'get',
                  url: `/iam/choerodon/v1/projects/${projectId}/users/search`,
                  data: {
                    userName: realName || '',
                    ids: [],
                  },
                };
              }
              if (appServiceId) {
                return {
                  method: 'post',
                  url: `/devops/v1/projects/${projectId}/users/app_services/${appServiceId}`,
                  data: {
                    userName: realName || '',
                    ids: [],
                  },
                };
              }
              return undefined;
            },
          },
        });
        break;
      }
    }
    return item;
  }),
});

export default Index;

export { mapping, transformLoadData };
